package ar.edu.unicen.pladema.main;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import ar.edu.unicen.pladema.resources.JarResourse;
import ar.edu.unicen.pladema.resources.ResourceManager;

/**
 * Aplicación.
 * @author Sebastian Perruolo &lt;sperruolo[at]alumnos.exa.unicen.edu.ar&gt;
 */
public abstract class AbstractShell {
	/** Ancho inicial. */
	private static final int DEFAULT_SIZE_WIDTH = 800;
	/** Alto inicial. */
	private static final int DEFAULT_SIZE_HEIGHT = 500;

	/** Display de la aplicación. */
	protected Display display = null;
	/** Shell principal de la aplicación. */
	protected Shell shell = null;
	
	/**
	 * Creador.
	 */
	public AbstractShell(Shell parent) {
		createMyWidgets(parent);
		layoutMyWidgets();
	}
	/**
	 * Se ubican los componentes.
	 */
	private void layoutMyWidgets() {
		SWTUtils.centerShell(shell);
		shell.setSize(DEFAULT_SIZE_WIDTH, DEFAULT_SIZE_HEIGHT);
		shell.setLayout(new FillLayout());
		layoutWidgets();
	}
	protected abstract void layoutWidgets();
	protected abstract void createWidgets();
	protected abstract void dispose();
	protected boolean mustClose() {
		return false;
	}
	/**
	 * Se crean los componentes.
	 */
	private void createMyWidgets(Shell parent) {
		if (parent == null) {
			display = new Display();
			shell = new Shell(display);
		} else {
			shell = new Shell(parent, SWT.APPLICATION_MODAL);
		}
		shell.setImage(
				JarResourse.getInstance().getResourceImage(shell.getDisplay(),"app")
			);
		shell.setText(ResourceManager.getInstance().getText("APPTITLE"));
		createWidgets();
	}
	/** Ejecuta la aplicación. */
	public void run() {
		shell.layout();
		shell.open();
		while ((!shell.isDisposed())&&(!mustClose())) {
			if (!shell.getDisplay().readAndDispatch()) {
				shell.getDisplay().sleep();
			}
		}
		dispose();
		if (display != null) {
			display.dispose();
		}
	}
}
